<?php

class Vendor extends Eloquent {

	protected $table = 'vendor';

	/**
	 * Condition: Unarchived Items.
	 * @author AngelaMisa 02/22/2015 2:25AM
	 * @param $query
	 * @return mixed
	 */
	public function scopeActive( $query ) {
		return $query->where($this->table . '.archived', 0);
	}
	
	/**
	 * Retrieves Products under Vendor.
	 * @author AngelaMisa 02/23/2015 9:51PM
	 * @param $query, $status
	 * @return mixed
	 */
	public function scopeHasOrders( $query, $status = null, $company = null ) {
		return $query->whereHas('products', function ( $query ) use ( $status, $company ) {
			$query->whereHas('orders', function ( $q ) use ( $status, $company ) {
				$q->where('order_product.archived', '0');

				if ( !is_null($status) ) $q->where( 'order_product.status', $status );
				if ( !is_null($company) ) $q->where( 'COMPANY_id', $company );
			});
		});
	}
	
	/**
	 * Retrieves Products under Vendor.
	 * Usage: Vendor::find(3)->products, Vendor::has('products')
	 * @author AngelaMisa 02/23/2015 9:51PM
	 * @return mixed
	 */
	public function products() {
		return $this->belongsToMany('Product', 'product_vendor', 'VENDOR_id', 'PRODUCT_id');
	}
	
	/**
	 * Retrieves Purchase Orders under Vendor.
	 * @author AngelaMisa 03/03/2015 12:32PM
	 * @return mixed
	 */
	public function purchaseOrders() {
		// Model, Foreign Key, Local Key
		return $this->hasMany('PurchaseOrder', 'VENDOR_id', 'id');
	}
}